const activeRegex = /^Active connections:\s+(\d+)/;
const readingWritingRegex = /^Reading:\s+(\d+).*Writing:\s+(\d+).*Waiting:\s+(\d+)/;
const handledRegex = /^\s+(\d+)\s+(\d+)\s+(\d+)/;

export interface NginxStatus {
  active: number;
  reading: number;
  writing: number;
  waiting: number;
  accepted: number;
  handled: number;
  requests: number;
}

export function parseNginxStatus(status: string): NginxStatus {
  const result: NginxStatus = {} as NginxStatus;
  const lines = status.split(/\n/);
  lines.forEach(function (line) {
    let matches: string[] | null;
    if (activeRegex.test(line)) {
      matches = activeRegex.exec(line);
      if (matches) {
        result.active = matches[1] ? parseInt(matches[1]) : 0;
      }
    } else if (readingWritingRegex.test(line)) {
      matches = readingWritingRegex.exec(line);
      if (matches) {
        result.reading = matches[1] ? parseInt(matches[1]) : 0;
        result.writing = matches[2] ? parseInt(matches[2]) : 0;
        result.waiting = matches[3] ? parseInt(matches[3]) : 0;
      }
    } else if (handledRegex.test(line)) {
      matches = handledRegex.exec(line);
      if (matches) {
        result.accepted = matches[1] ? parseInt(matches[1]) : 0;
        result.handled = matches[2] ? parseInt(matches[2]) : 0;
        result.requests = matches[3] ? parseInt(matches[3]) : 0;
      }
    }
  });
  return result;
}
